<template>
  <div class="app-container">
    <el-row :gutter="20">
      <splitpanes :horizontal="this.$store.getters.device === 'mobile'" class="default-theme">
        <!--分类数据-->
        <pane size="16">
          <el-col>
            <div class="head-container">
              <el-input v-model="cateName" placeholder="请输入分类名称" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px" />
            </div>
            <div class="head-container">
              <el-tree :data="cateOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current @node-click="handleNodeClick" />
            </div>
          </el-col>
        </pane>
        <!--产品数据-->
        <pane size="84">
          <el-col>
            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
              <el-form-item label="岗位名称" prop="prodName">
                <el-input v-model="queryParams.title" placeholder="请输入岗位名称" clearable style="width: 240px" @keyup.enter.native="handleQuery" />
              </el-form-item>
              <el-form-item label="状态" prop="status">
                <el-select v-model="queryParams.status" placeholder="招聘信息状态" clearable style="width: 240px">
                  <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
              <el-col :span="1.5">
                <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['system:prod:add']">新增</el-button>
              </el-col>
              <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
            </el-row>

            <el-table v-loading="loading" :data="articleList" @selection-change="handleSelectionChange">
              <el-table-column type="selection" width="50" align="center"  :show-overflow-tooltip="true"/>
              <el-table-column label="岗位名称" align="center" key="title" prop="title" v-if="columns.title.visible" :show-overflow-tooltip="true" />
              <el-table-column label="招聘企业" align="center" key="subTitle" prop="subTitle" v-if="columns.subTitle.visible" :show-overflow-tooltip="true" />
              <el-table-column label="排序" align="center" key="sort" prop="sort" v-if="columns.sort.visible" :show-overflow-tooltip="true" />
              <el-table-column label="是否上架" align="center" key="status" v-if="columns.status.visible" :show-overflow-tooltip="true">
                <template slot-scope="scope">
                  <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
                </template>
              </el-table-column>
              <el-table-column label="创建时间" align="center" prop="createTime" v-if="columns.createTime.visible" width="160">
                <template slot-scope="scope">
                  <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
                <template slot-scope="scope" v-if="scope.row.userId !== 1">
<!--                  <el-button size="mini" type="text" icon="el-icon-edit" @click="preview(scope.row)">预览</el-button>-->
                  <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:user:edit']">修改</el-button>
                  <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['system:user:remove']">删除</el-button>
                </template>
              </el-table-column>
            </el-table>

            <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
          </el-col>
        </pane>
      </splitpanes>
    </el-row>

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="70%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="岗位名称" prop="title">
              <el-input v-model="form.title" placeholder="请输入岗位名称" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="招聘企业" prop="subTitle">
              <el-input v-model="form.subTitle" placeholder="请输入招聘企业" maxlength="30" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属分类" prop="cateId">
              <treeselect v-model="form.cateId" :options="enabledCateOptions" :disable-branch-nodes="true" :show-count="true" placeholder="请选择所属分类"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="招聘人数" prop="author">
              <el-input-number v-model="form.author" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工作地点" prop="source">
              <el-select v-model="form.source" placeholder="工作地点" clearable style="width: 240px">
                <el-option v-for="dict in dict.type.sys_recruitment_region" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="岗位类型" prop="headTitle">
              <el-select v-model="form.headTitle" placeholder="岗位类型" clearable style="width: 240px">
                <el-option v-for="dict in dict.type.sys_position_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="sort">
              <el-input-number v-model="form.sort" controls-position="right" :min="0" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="上线状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>

        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="岗位职责">
              <editor v-model="form.duty" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="任职要求">
              <editor v-model="form.require" :min-height="192"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>



<script>
import {listArticle, cateTreeSelect, getArticle, addArticle, updateArticle, delArticle, changeArticleStatus} from "@/api/system/article"
import {listCate} from "@/api/system/cate"
import {getSite, getToken} from "@/utils/auth"
import Treeselect from "@riophae/vue-treeselect"
import "@riophae/vue-treeselect/dist/vue-treeselect.css"
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"
import {listToString, splitImages, splitObject} from "@/api/tool/upload";
export default {
  name: "pdContent",
  dicts: ['sys_normal_disable','sys_recruitment_region','sys_position_type'],
  components: { Treeselect, Splitpanes, Pane },
  props: {
    // 图片数量限制
    limit: {
      type: Number,
      default: 1,
    },
    // 大小限制(MB)
    fileSize: {
      type: Number,
      default: 50,
    },
    // 文件类型, 例如['png', 'jpg', 'jpeg']
    fileType: {
      type: Array,
      default: () => ["png", "jpg", "jpeg"],
    },
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品表格数据
      articleList: null,
      // 弹出层标题
      title: "",
      // 所有部门树选项
      cateOptions: undefined,
      CateOptions: undefined,
      // 过滤掉已禁用分类树选项
      enabledCateOptions: undefined,
      // 是否显示弹出层
      open: false,
      // 分类名称
      cateName: undefined,
      cateIds: [],
      // 表单参数
      form: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      // 查询参数
      queryParams: {
        tenantId: getSite(),
        typeId: 2,
        articleType: 6,
        pageNum: 1,
        pageSize: 10,
        prodName: undefined,
        status: undefined
      },
      // 查询参数
      editQueryParams: {
        tenantId: getSite(),
        typeId: 6
      },
      // 列信息
      columns: {
        title: { label: '标题', visible: true },
        subTitle: { label: '副标题', visible: true },
        sort: { label: '排序', visible: true },
        status: { label: '是否上架', visible: true },
        createTime: { label: '创建时间', visible: true }
      },
      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        cateId: [
          { required: true, message: "分类不能为空", trigger: "blur" }
        ],
        sort: [
          { required: true, message: "排序不能为空", trigger: "blur" }
        ]
      },
      // 上传的图片服务器地址
      uploadImgUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      // 上传图片个数
      number: 0,
      headers: {
        Authorization: "Bearer " + getToken(),
      },
      previewUrl: process.env.VUE_APP_PROD_URL,
      fileList: [],   //产品图
      imageList: [],  //列表缩略图
      contentIconList: [], //介绍icon
      uploadList: [], //临时上传列表
      dialogVisible: false,
      dialogImageUrl: "",
    }
  },
  watch: {
    // 根据名称筛选部门树
    cateName(val) {
      this.$refs.tree.filter(val)
    }
  },
  created() {
    this.getList()
    this.getCateTree()
  },
  computed: {
    // 是否显示提示
    showTip() {
      return this.isShowTip && (this.fileType || this.fileSize);
    },
  },
  methods: {
    /** 查询产品列表 */
    getList() {
      this.loading = true
      listArticle(this.queryParams).then(response => {
          this.articleList = response.rows
          this.total = response.total
          this.loading = false
        }
      )
    },
    /** 查询分类下拉树结构 */
    getCateTree() {
      cateTreeSelect(this.editQueryParams).then(response => {
        this.cateOptions = response.data
        this.enabledCateOptions = this.filterDisabledCate(JSON.parse(JSON.stringify(response.data)))
      });
      listCate(this.editQueryParams).then(response => {
        this.CateOptions = response.data;
      })
    },
    // 过滤禁用的分类
    filterDisabledCate(cateList) {
      return cateList.filter(cate => {
        if (cate.disabled) {
          return false
        }
        if (cate.children && cate.children.length) {
          cate.children = this.filterDisabledCate(cate.children)
        }
        return true
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.cateId = data.id
      this.handleQuery()
    },
    // 状态修改
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用"
      this.$modal.confirm('确认要' + text + '"' + row.title + '"的数据吗？').then(function() {
        return changeArticleStatus(row.articleId, row.status)
      }).then(() => {
        this.$modal.msgSuccess(text + "成功")
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0"
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        articleId: undefined,
        cateId: undefined,
        prodName: undefined,
        status: "0",
        Content: undefined,
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.queryParams.deptId = undefined
      this.$refs.tree.setCurrentKey(null)
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加信息"
      //产品图
      this.fileList = [];
      //列表缩略图
      this.imageList = [];
      //介绍icon
      this.contentIconList = [];
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const articleId = row.articleId
      getArticle(articleId).then(response => {
        let formData = response.data
        if(formData.content){
          let content = JSON.parse(formData.content);
          formData.duty = content.duty;
          formData.require = content.require;
        }
        this.form = formData
        this.open = true
        this.title = "修改信息"
        //列表缩略图
        this.imageList = [];
        if(this.form.images){
          const imageArr = this.form.images.split(';');
          for (var i = 0; i < imageArr.length; i++) {
            this.imageList.push({ name: imageArr[i], fileName: imageArr[i],url: process.env.VUE_APP_BASE_API + imageArr[i] });
          }
        }
        //介绍icon
        this.contentIconList = [];
        if(this.form.linkUrl){
          const imageArr = this.form.linkUrl.split(';');
          for (var i = 0; i < imageArr.length; i++) {
            this.contentIconList.push({ name: imageArr[i], fileName: imageArr[i],url: process.env.VUE_APP_BASE_API + imageArr[i] });
          }
        }
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 租户ID
          this.form.tenantId = getSite();
          this.form.typeId = this.queryParams.typeId;
          this.form.articleType = this.queryParams.articleType;
          // 列表缩略图
          this.form.images = splitImages(this.imageList);
          //介绍icon
          this.form.linkUrl = splitImages(this.contentIconList);
          const content = {duty : this.form.duty, require: this.form.require}
          this.form.content = btoa(unescape(encodeURIComponent(JSON.stringify(content))));
          if (this.form.articleId != undefined) {
            updateArticle(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addArticle(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const articleId = row.articleId
      this.$modal.confirm('是否确认删除名称为"' + row.title + '"的数据项？').then(function() {
        return delArticle(articleId)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
    /**产品预览 **/
    preview(row){
      const url = this.previewUrl.replace('#{cateId}',row.cateId).replace('#{articleId}',row.articleId);
      window.open(url);
    },

    // 预览
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },

    //分类图片方法
    // 上传前loading加载
    handleCateImageBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
      this.number++;
    },
    // 上传成功回调
    handleUploadCateImageSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ name: res.newFileName, fileName: res.fileName,url: res.url });
        this.uploadedCateImageSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.imageUpload.handleRemove(file);
        this.uploadedCateImageSuccessfully();
      }
    },
    // 上传结束处理
    uploadedCateImageSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.imageList = this.imageList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", listToString(this.baseUrl,this.imageList));
        this.$modal.closeLoading();
      }
    },
    // 文件个数超出
    handleCateImageExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleCateImageUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },
    // 删除图片
    handleCateImageUploadDelete(file) {
      const findex = this.imageList.map(f => f.name).indexOf(file.name);
      if (findex > -1) {
        this.imageList.splice(findex, 1);
        this.$emit("input", listToString(this.baseUrl,this.imageList));
      }
    },
    // 预览
    handleCateImagePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //介绍ICON图片上传
    // 上传前loading加载
    handleContentIconBeforeUpload(file) {
      let isImg = false;
      if (this.fileType.length) {
        let fileExtension = "";
        if (file.name.lastIndexOf(".") > -1) {
          fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
        }
        isImg = this.fileType.some(type => {
          if (file.type.indexOf(type) > -1) return true;
          if (fileExtension && fileExtension.indexOf(type) > -1) return true;
          return false;
        });
      } else {
        isImg = file.type.indexOf("image") > -1;
      }

      if (!isImg) {
        this.$modal.msgError(`文件格式不正确, 请上传${this.fileType.join("/")}图片格式文件!`);
        return false;
      }
      if (this.fileSize) {
        const isLt = file.size / 1024 / 1024 < this.fileSize;
        if (!isLt) {
          this.$modal.msgError(`上传头像图片大小不能超过 ${this.fileSize} MB!`);
          return false;
        }
      }
      this.$modal.loading("正在上传图片，请稍候...");
      this.number++;
    },
    // 上传成功回调
    handleUploadContentIconSuccess(res, file) {
      if (res.code === 200) {
        this.uploadList.push({ name: res.newFileName, fileName: res.fileName,url: res.url });
        this.uploadedContentIconSuccessfully();
      } else {
        this.number--;
        this.$modal.closeLoading();
        this.$modal.msgError(res.msg);
        this.$refs.imageUpload.handleRemove(file);
        this.uploadedContentIconSuccessfully();
      }
    },
    // 上传结束处理
    uploadedContentIconSuccessfully() {
      if (this.number > 0 && this.uploadList.length === this.number) {
        this.contentIconList = this.contentIconList.concat(this.uploadList);
        this.uploadList = [];
        this.number = 0;
        this.$emit("input", listToString(this.baseUrl,this.contentIconList));
        this.$modal.closeLoading();
      }
    },
    // 文件个数超出
    handleContentIconExceed() {
      this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
    },
    // 上传失败
    handleContentIconUploadError() {
      this.$modal.msgError("上传图片失败，请重试");
      this.$modal.closeLoading();
    },
    // 删除图片
    handleContentIconUploadDelete(file) {
      const findex = this.contentIconList.map(f => f.name).indexOf(file.name);
      if (findex > -1) {
        this.contentIconList.splice(findex, 1);
        this.$emit("input", listToString(this.baseUrl,this.contentIconList));
      }
    },
  }
}
</script>
